#!/bin/sh

BACKUP_DEST=/export/backups
BACKUP_FS=external/export/backups
BACKUP_HOST=backups
BACKUP_USER=operator

if [ "$DEBUG" = "" ]
then
    ECHO=""
else
    ECHO=echo
fi

case $(uname) in
    Darwin)
	dump_list=$(df -T ufs,hfs | awk 'NR != 1 { print $NF }') ;
	extra_flags="--extended-attribues"
	hostname=$(hostname -s) ;;
    FreeBSD)
	dump_list=$(mount -p -t ufs,zfs | awk ' { print $2 }') ;
	extra_flags="--acls --xattrs"
	hostname=$(hostname -s) ;;
    SunOS)
	dump_list=$(/usr/gnu/bin/df -P -t zfs -t ufs | awk 'NR != 1 && !/^external/ { print $NF }') ;
	extra_flags=""
	hostname=$(hostname) ;;
esac

if [ $# -eq 0 ]
then
    dump_name=$hostname
else
    dump_name=$1; shift
    dump_list="$@"
fi

for dir in $dump_list
do
    case $dir in
	/tmp*) echo Skipping $dir ;;
	*) $ECHO rsync --verbose --archive  --hard-links --delete --one-file-system --no-whole-file --exclude /.zfs $dir $BACKUP_DEST/$dump_name$dir ;;
    esac
done

SNAPSHOT_COMMAND="/usr/sbin/zfs snapshot -r $BACKUP_FS/$dump_name@$(date +%F)"
if [ "$BACKUP_HOST" = "$hostname" ]
then
    $ECHO $SNAPSHOT_COMMAND
else
    $ECHO su $BACKUP_USER -c "ssh $BACKUP_HOST 'pfexec $SNAPSHOT_COMMAND'"
fi
